package com.xbongbong.paas.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xbongbong.paas.pojo.linkdata.dto.DataLinkageDTO;
import com.xbongbong.paas.pojo.linkdata.vo.DataLinkageVO;
import com.xbongbong.paas.service.LinkRelyDataService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Objects;

/**
 * @author 吴峰
 * @date 2022/03/28 11:03
 */
@RestController
@RequestMapping(value = XbbProConstant.API_ROOT_PREFIX + "/data")
public class LinkDataController {

    @Resource
    private LinkRelyDataService linkRelyDataService;

    /**
     * 数据联动 子表单的子字段设置数据联动
     * @param linkDataDTO
     * @param br
     * @return
     */
    @RequestMapping(value = "/linkage", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String add(@RequestBody @Valid DataLinkageDTO linkDataDTO, BindingResult br) {
        XbbResponse<DataLinkageVO> response;
        if (br.hasErrors()){
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                DataLinkageVO linkDataVO = linkRelyDataService.linkage(linkDataDTO);
                response = new XbbResponse<>(linkDataVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }
}
